package com.zh.note.demo.juc;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class Mydata { // 资源类
    public ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

    public void add() {
        threadLocal.set(threadLocal.get() + 1);
    }
}

public class ThreadLocalDemo3 {
    public static void main(String[] args) {
        Mydata mydata = new Mydata();
        // 模拟一个银行由三个窗口办理业务
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        try {
            // 10个顾客办理业务
            for (int i = 0; i < 10; i++) {
                int finalI = i;
                threadPool.submit(() -> {
                    try {
                        Integer beforeInt = mydata.threadLocal.get();
                        mydata.add();
                        Integer afterInt = mydata.threadLocal.get();
                        System.out.println(Thread.currentThread().getName() + "\t" + "工作窗口，受理第：" + finalI + "个顾客业务\t" + "beforeInt: " + beforeInt + "\t" + "afterInt: " + afterInt);
                    } finally {
                        mydata.threadLocal.remove();
                    }
                });
            }
        } catch (Exception e) {

        } finally {
            threadPool.shutdown();
        }
    }
}
